package org.droid.campusorder.manager;

/**
 * @author Jerry
 * 网络连接请求
 */

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.droid.campusorder.common.DroidException;
import org.droid.campusorder.common.DroidException.NetworkException;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Debug;

public class NetManager {
	private Context c;
	private String tag = "NetManager";
	static private NetManager instance = null;
	private String CHARTSET = "utf8";
	private int TIMEOUT = 5000;// 单位 毫秒
	static private String COOKIE;

	static public NetManager getInstance(Context c) {

		if (instance == null) {
			instance = new NetManager();
			instance.c = c.getApplicationContext();
		}
		return instance;
	}

	private NetManager() {

	}

	public String dopostAsString(String url, Hashtable<String, String> ht)
			throws NetworkException {
		try {
			DefaultHttpClient httpclient = getHttpClient();
			// Log.d(tag, url);
			HttpPost req = new HttpPost(url);
			if (COOKIE != null && !COOKIE.equals(""))
				req.setHeader("Cookie", COOKIE);
			req.getParams().setParameter(
					HttpConnectionParams.CONNECTION_TIMEOUT, TIMEOUT);

			List<NameValuePair> valuepairs = new ArrayList<NameValuePair>();// post提交的名值对
			Enumeration<String> en = ht.keys();
			for (; en.hasMoreElements();) {// 遍历hashtable 获取key
				String key = en.nextElement();
				// Log.d(tag, key);
				// Log.d(tag, ht.get(key));
				valuepairs.add(new BasicNameValuePair(key, ht.get(key)));
			}

			req.setEntity(new UrlEncodedFormEntity(valuepairs, HTTP.UTF_8));
			HttpResponse rep = httpclient.execute(req);
			System.out.println("返回：" + rep.getStatusLine());
			Header[] headers = rep.getHeaders("Set-Cookie");
			StringBuffer sb = new StringBuffer();
			for (Header h : headers) {
				sb.append(h.getValue() + ";");
			}
			if (!sb.toString().equals(""))
				COOKIE = sb.toString();
			InputStream in = rep.getEntity().getContent();
			BufferedReader r = new BufferedReader(new InputStreamReader(in));
			sb = new StringBuffer();
			String line = "";
			while ((line = r.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			return sb.toString();
		} catch (Exception e) {
			System.out.println(e.toString());
			throw new DroidException.NetworkException(e.toString(), e);
		}
	}

	public InputStream dopostAsStream(String url, Hashtable<String, String> ht)
			throws NetworkException {
		try {
			DefaultHttpClient httpclient = getHttpClient();
			// Log.d(tag, url);
			HttpPost req = new HttpPost(url);
			if (COOKIE != null && !COOKIE.equals(""))
				req.setHeader("Cookie", COOKIE);
			req.getParams().setParameter(
					HttpConnectionParams.CONNECTION_TIMEOUT, TIMEOUT);

			List<NameValuePair> valuepairs = new ArrayList<NameValuePair>();// post提交的名值对
			Enumeration<String> en = ht.keys();
			for (; en.hasMoreElements();) {// 遍历hashtable 获取key
				String key = en.nextElement();
				// Log.d(tag, key);
				// Log.d(tag, ht.get(key));
				System.out.println(key + "----->" + ht.get(key));
				valuepairs.add(new BasicNameValuePair(key, ht.get(key)));
			}

			req.setEntity(new UrlEncodedFormEntity(valuepairs, HTTP.UTF_8));
			HttpResponse rep = httpclient.execute(req);

			Header[] headers = rep.getHeaders("Set-Cookie");
			StringBuffer sb = new StringBuffer();
			for (Header h : headers) {
				sb.append(h.getValue() + ";");
			}
			if (!sb.toString().equals(""))
				COOKIE = sb.toString();
			// Log.d(tag, COOKIE);
			System.out.println(tag + ":" + COOKIE);
			HttpEntity entity = rep.getEntity();

			InputStream in = entity.getContent();
			return in;
		} catch (Exception e) {
			throw new DroidException.NetworkException(e.toString(), e);
		}
	}

	public String dogetAsString(String url) throws NetworkException {
		try {
			DefaultHttpClient httpclient = getHttpClient();
			HttpGet req = new HttpGet(url);
			if (COOKIE != null && !COOKIE.equals(""))
				req.setHeader("Cookie", COOKIE);
			req.getParams().setParameter(
					HttpConnectionParams.CONNECTION_TIMEOUT, TIMEOUT);
			HttpResponse rep = httpclient.execute(req);
			Header[] headers = rep.getHeaders("Set-Cookie");
			StringBuffer sb = new StringBuffer();
			for (Header h : headers) {
				sb.append(h.getValue() + ";");
			}
			if (!sb.toString().equals(""))
				COOKIE = sb.toString();
			InputStream in = rep.getEntity().getContent();
			BufferedReader r = new BufferedReader(new InputStreamReader(in,
					CHARTSET));
			sb = new StringBuffer();
			String line = "";
			while ((line = r.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			return sb.toString();
		} catch (Exception e) {
			throw new DroidException.NetworkException(e.toString(), e);
		}
	}

	public DefaultHttpClient getHttpClient() {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		if (isWiFiActive()) {

		} else {
			String proxyHost = android.net.Proxy.getDefaultHost();
			if (proxyHost != null) {
				HttpHost proxy = new HttpHost(android.net.Proxy
						.getDefaultHost(), android.net.Proxy.getDefaultPort());
				httpClient.getParams().setParameter(
						ConnRoutePNames.DEFAULT_PROXY, proxy);
			} else {

			}
		}
		httpClient.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,
				TIMEOUT);
		return httpClient;
	}

	private boolean isWiFiActive() {
		ConnectivityManager connectivity = (ConnectivityManager) c
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getTypeName().equals("WIFI")
							&& info[i].isConnected()) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * 判断是否有可用网络
	 */
	public static boolean isNetworkAvailable(Context ctx) {
		ConnectivityManager connectivity = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
			if (networkInfo == null) {
				return false;
			} else {
				if (networkInfo.isAvailable()) {
					return true;
				} else {
					return false;
				}
			}
		}

	}// end isNetworkAvailable
}
